package com.xtianzhuang.www.shiro;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.xtianzhuang.www.entity.TfUUser;
import com.xtianzhuang.www.entity.VUserPermission;
import com.xtianzhuang.www.entity.VUserRole;
import com.xtianzhuang.www.service.impl.SystemServiceBiz;
import com.xtianzhuang.www.service.impl.UserServiceBiz;
import com.xtianzhuang.www.utils.SpringContextHolder;

public class Realm extends AuthorizingRealm {
	/**
	 * 授权：验证权限时调用
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		TfUUser user = (TfUUser) principals.getPrimaryPrincipal();
		// 查询用户信息
		UserServiceBiz userServiceBiz = (UserServiceBiz) SpringContextHolder.getBean("userServiceBiz");
		SystemServiceBiz systemServiceBiz = (SystemServiceBiz) SpringContextHolder.getBean("systemServiceBiz");
		List<VUserRole> list = userServiceBiz.getUserRole(user.getUserId());
		Set<String> roles = new HashSet<>();
		for (VUserRole role : list) {
			if (StringUtils.isNotBlank(role.getRoleName())) {
				roles.add(role.getRoleName());
			}
		}
		 // 当前用户所有权限
		List<VUserPermission> list2 = systemServiceBiz.getPermissions(user.getUserId());
        Set<String> permissions = new HashSet<>();
		for (VUserPermission item : list2) {
            if (StringUtils.isNotBlank(item.getPermissionValue())) {
                permissions.add(item.getPermissionValue());
            }
        }
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.setRoles(roles);
		simpleAuthorizationInfo.setStringPermissions(permissions);
		return simpleAuthorizationInfo;
	}

	/**
	 * 认证：登录时调用
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		String username = (String) token.getPrincipal();
		String password = new String((char[]) token.getCredentials());
		// 查询用户信息
		UserServiceBiz userServiceBiz = (UserServiceBiz) SpringContextHolder.getBean("userServiceBiz");
		TfUUser tfUUser = userServiceBiz.selectUserByUserName(username);
		if (null == tfUUser) {
			throw new UnknownAccountException("账号不存在");
		}
		if (!tfUUser.getPassword().equals(password)) {
			throw new IncorrectCredentialsException("账号或者密码错误");
		}
		return new SimpleAuthenticationInfo(tfUUser, password, getName());
	}

}
